/*
 * Copyright (c) 2012 Robert Burrell Donkin robertburrelldonkin.name
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
package walrus.text;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.nio.CharBuffer;

public class WordCountApp {

	private static final String TRANSCRIPT_FILE = "TEXT.txt";

	public static void main(String[] args) throws Exception {
		

		WordCountApp app = new WordCountApp();
		app.read("/home/rob/documents/speech/poems/theotherpages/");
		app.print(System.out);
	}
	
	private void print(PrintStream out) {
			WordCounter counter = new WordCounter();
			counter.setIgnoreCase(true);
			counter.load(parser.getWords()).printTo(out);
	}

	private final CharBuffer buffer = CharBuffer.allocate(2048);
	private final SimpleWordParser parser = new SimpleWordParser();
	
	public void read(String name) throws IOException {
		read(new File(name));
	}
	
	public void read(final File file) throws IOException {
		if (file.isDirectory()) {
			for (File childFile: file.listFiles()) {
				if (childFile.equals(file.getParentFile())) {
					System.out.println("Ignoring circular directory");
				} else {
					read(childFile);
				}
			}
		} else if (TRANSCRIPT_FILE.equals(file.getName())) {
			Reader reader = new InputStreamReader(new BufferedInputStream(new FileInputStream(file)), "UTF-8");
			readAll(reader);
		} else {
		}
	}

	public void readAll(Reader reader) throws IOException {
		while (read(reader));
		parser.eof();
	}


	private boolean read(Reader reader) throws IOException {
		buffer.clear();
		int read = reader.read(buffer);
		buffer.flip();
		for (int i=0;i<read;i++) {
			final char next = buffer.get();
			parser.process(next);
		}
		return read >= 0;
	}
}
